<?php

namespace App\Containers\AppSection\User\Actions;

use App\Containers\AppSection\Authorization\Tasks\SyncUserToRoleTask;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Tasks\FindLatestProfileByUserIdTask;
use App\Containers\AppSection\User\Models\User;
use App\Containers\AppSection\User\Tasks\FindUserByIdTask;
use App\Containers\AppSection\User\Tasks\UpdateUserTask;
use App\Containers\AppSection\User\UI\API\Requests\UpdateUserRequest;
use App\Ship\Parents\Actions\Action;

class UpdateUserAction extends Action
{
    public function run(UpdateUserRequest $request): User
    {
        $user = app(FindUserByIdTask::class)->run($request->id);

        $data = [
            'other_information' => $request->getInputByKey('other_information')
        ];

        if (!empty($request->getInputByKey('email'))) {
            $data['email'] = $request->getInputByKey('email');
            $data['email_verified_at'] = now();
        }
        if (!empty($request->getInputByKey('phone'))) {
            $data['phone'] = $request->getInputByKey('phone');
            $data['phone_verified_at'] = now();
        }
        if (!empty($request->getInputByKey('fio'))) {
            $data['fio'] = $request->getInputByKey('fio');
        }
        if (!empty($request->getInputByKey('password'))) {
            $data['password'] = $request->getInputByKey('password');
        }

        $roles = $request->getInputByKey('roles');

        if (is_array($roles) && count($roles) > 0) {
            app(SyncUserToRoleTask::class)->run($user, $roles);
        }

        app(UpdateUserTask::class)->run($data, $user->id);

        $profile = app(FindLatestProfileByUserIdTask::class)->run($user->id);

        app(CreateLogTask::class)->run($profile->id, "Данные пользователя №{$user->id} изменены (админ)", 'user');
        app(CreateLogTask::class)->run($request->profile()->id, "Данные пользователя №{$user->id} изменены", 'user');

        return app(FindUserByIdTask::class)->run($user->id);
    }
}
